package com.heima.user.service.impl;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDTO;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.common.MD5Utils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
@Transactional
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper,ApUser> implements ApUserService {
    /**
     * app端登录
     * @param loginDTO
     * @return
     */
    @Override
    public ResponseResult login(LoginDTO loginDTO) {

      /*  //正常登录，用户名和密码非空
        if (loginDTO.getPhone() != null && loginDTO.getPassword() != null){
            //先查用户是否存在
            LambdaQueryWrapper<ApUser> queryWrapper = new LambdaQueryWrapper<>();
            ApUser apUser = getOne(queryWrapper.eq(ApUser::getPhone, loginDTO.getPhone()));
            if (apUser == null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"用户不存在");
            }
                //用户存在，检查密码是否正确
                String salt = apUser.getSalt();
                String password = loginDTO.getPassword();
                String s = MD5Utils.encodeWithSalt(password, salt);
                if (!s.equals(apUser.getPassword())){
                    //密码不正确
                    return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
                }else {
                    //密码正确
                    String token = AppJwtUtil.getToken(Long.valueOf(apUser.getId()));
                    HashMap<String, Object> hashMap = new HashMap<>();
                    apUser.setSalt("");
                    apUser.setPassword("");
                    hashMap.put("user",apUser);
                    hashMap.put("token",token);
                    return ResponseResult.okResult(hashMap);
                }

        }else {
            //用户名和密码为空
            HashMap<String, Object> hashMap = new HashMap<>();
            String token = AppJwtUtil.getToken(0L);
            hashMap.put("token",token);
            return ResponseResult.okResult(hashMap);
        }
*/

        //1.正常登录（手机号+密码登录）
        if (!StringUtils.isBlank(loginDTO.getPhone()) && !StringUtils.isBlank(loginDTO.getPassword())) {
            //1.1查询用户
            ApUser apUser = getOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone,loginDTO.getPhone()));
            if (apUser == null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"用户不存在");
            }

            //1.2 比对密码
            String salt = apUser.getSalt();
            String pswd = loginDTO.getPassword();
            pswd = DigestUtils.md5DigestAsHex((pswd + salt).getBytes());
            if (!pswd.equals(apUser.getPassword())) {
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            //1.3 返回数据  jwt
            Map<String, Object> map = new HashMap<>();
            map.put("token", AppJwtUtil.getToken(apUser.getId().longValue()));
            apUser.setSalt("");
            apUser.setPassword("");
            map.put("user", apUser);
            return ResponseResult.okResult(map);
        } else {
            //2.游客  同样返回token  id = 0
            Map<String, Object> map = new HashMap<>();
            map.put("token", AppJwtUtil.getToken(0l));
            return ResponseResult.okResult(map);
        }

    }
}


